package com.vf.admin.client.controller;


import cn.hutool.core.util.ObjectUtil;
import com.vf.admin.client.common.ClientBaseController;
import com.vf.admin.client.common.ClientConstants;
import com.vf.admin.client.common.RedisKeys;
import com.vf.admin.client.service.*;
import com.vf.admin.common.entity.Result;
import com.vf.admin.common.redis.RedisUtil;
import com.vf.admin.common.splitpage.SplitPageBean;
import com.vf.admin.fiwork.controller.AppDailyTasController;
import com.vf.admin.miaodong.entity.*;
import com.vf.admin.utils.AgeUtils;
import com.vf.admin.utils.StringEx;
import com.vf.admin.utils.TimeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

import static com.vf.admin.common.Constants.guizuCacheMap;

/**
 * 家族控制器
 */
@Controller
@CrossOrigin
@RequestMapping("/app/family")
public class AppFamilyController extends ClientBaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private AppFamilyService appFamilyService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private AppUserService appUserService;
    @Autowired
    private AppSetupService appSetupService;
    @Autowired
    private AppFamilyMemberService appFamilyMemberService;
    @Autowired
    private AppQianDaoRecordService appQianDaoRecordService;
    @Autowired
    private AppMingxiJinbiService appMingxiJinbiService;
    @Autowired
    private AppFamilyPrestigeService appFamilyPrestigeService;
    @Autowired
    private AppFamilyIdentityService appFamilyIdentityService;
    @Autowired
    private AppFamilySetLevelService appFamilySetLevelService;
    @Autowired
    private AppMingXiZuanShiService appMingXiZuanShiService;
    @Autowired
    private AppDailyTasController appDailyTasController;
    @Autowired
    private SystemAlertService systemAlertService;

    /**
     * 创建家族
     *
     * @param appFamily
     * @return
     */
    @RequestMapping("/createFamily")
    @ResponseBody
    public Result createFamily(HttpServletRequest request, AppFamily appFamily) {
        Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));
        AppUser appUser = appUserService.get(userId);
        if(!appUserService.isVip(userId)) {
            return this.errorJSON("VIP用户才可创建家族");
        }
        if (ObjectUtil.isEmpty(appUser)) {
            return this.errorJSON("用户不存在");
        }
        AppSetup setup = appSetupService.get();
        if (setup.getCreateFamilyForDiamonds() != 0) {
            if (new BigDecimal(String.valueOf(setup.getCreateFamilyForDiamonds())).compareTo(appUser.getDiamonds()) > 0) {
                return this.errorJSON("钻石余额不足");
            }
        }
        AppFamily byLeaderId = appFamilyService.findByLeaderId1(userId);
        if (byLeaderId != null) {
//            return this.errorJSON("家族已存在，不可再创建");
            if(byLeaderId.getStatus()==3){
                return this.errorJSON("家族已存在，待审核");
            }
            if(byLeaderId.getStatus() == 0 || byLeaderId.getStatus() ==1){
                return this.errorJSON("家族已存在，不可再创建");
            }
        }
        if(redisUtil.hasKey(RedisKeys.FAMILY_ID)){
            Integer familyId = (Integer) redisUtil.get(RedisKeys.FAMILY_ID);
            appFamily.setFamilyid(familyId);
            redisUtil.set(RedisKeys.FAMILY_ID,familyId+1);
        }else{
            Random random = new Random();
            int i = random.nextInt(99999)+10000000;
            appFamily.setFamilyid(i);
            redisUtil.set(RedisKeys.FAMILY_ID,i+1);
        }
        Boolean family = appFamilyService.createFamily(userId, setup.getCreateFamilyForDiamonds(), appFamily);
        appDailyTasController.getAwardOnce(userId, ClientConstants.TaskOnce.JOIN_FAMILY);
        if (family) {
            return this.sucessJSON(appFamily, "创建成功");
        } else {
            return this.errorJSON("创建失败");
        }
    }

    /**
     * 加入家族待审核列表
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/reviewedList")
    public Result reviewedList(HttpServletRequest request)
    {
        try {
            Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));
            AppUser appUser = appUserService.get(userId);
            if (StringUtils.isEmpty(appUser)) {
                return this.errorJSON("用户不存在");
            }
            AppFamily byLeaderId = appFamilyService.findByLeaderId(appUser.getId());
            if(byLeaderId == null || byLeaderId.getStatus()!=0){
                return this.errorJSON("家族不存在或被封禁");
            }
            List<AppFamilyMember> familyReviewedMemberByFid = appFamilyMemberService.getFamilyReviewedMemberByFid(byLeaderId.getId());

            return this.sucessJSON(familyReviewedMemberByFid,"获取成功");
        }catch (Exception e){
            logger.error("加入家族待审核列表异常", e);
            return this.errorJSON("系统繁忙，请稍后重试");
        }
    }




    /**
     * 申请加入家族
     *
     * @param request
     * @param appFamilyMember
     * @return
     */
    @RequestMapping("/addFamilyMember")
    @ResponseBody
    public Result addFamilyMember(HttpServletRequest request, AppFamilyMember appFamilyMember) {
        try {
            Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));
            AppUser appUser = appUserService.get(userId);
            if (StringUtils.isEmpty(appUser)) {
                return this.errorJSON("用户不存在");
            }

            if (StringUtils.isEmpty(appFamilyMember.getAdd_reason())) {
                return this.errorJSON("请填写申请加入理由");
            }

            AppFamilyMember byUserId = appFamilyMemberService.findByUserId(userId);
            if (byUserId != null) {
                if (byUserId.getStatus() == 1) {
                    return this.errorJSON("只能加入一个家族");
                }
                if (byUserId.getStatus() == 0) {
                    return this.errorJSON("您已存在申请加入的家族，请等待族长审核");
                }
            }
            appFamilyMember.setUserid(userId);
            AppSetup setup = appSetupService.get();
            if (setup.getQuitFamilyForDay() != 0) {
                if (redisUtil.hasKey(RedisKeys.QUIT_FAMILY + userId + appUser.getLoginname())) {
                    return this.errorJSON("退出家族后" + setup.getQuitFamilyForDay() + "天内不可再加入新家族");
                }
            }
            AppFamily appFamily = appFamilyService.findbyId(appFamilyMember.getFid());
            if (appFamily == null) {
                return this.errorJSON("家族不存在或被封禁");
            }
            AppFamilySetLevel levelInfoByLevel = appFamilySetLevelService.getLevelInfoByLevel(appFamily.getFamilylevel());
            if(appFamily.getFamilycount().compareTo(levelInfoByLevel.getFamilyMaxCount())>=0){
                return this.errorJSON("家族成员已满，不可加入");
            }
            appFamilyMember.setFamilyid(appFamily.getFamilyid());
            AppFamilyMember info = appFamilyMemberService.findInfo(appFamilyMember);
            if(info != null){
                if(info.getStatus() == 1){
                    return this.errorJSON("您已加入该家族");
                }
                if(info.getStatus() == 0){
                    return this.errorJSON("请等待族长审核");
                }
            }
            appFamilyMember.setCreatetime(new Date());
            appFamilyMember.setUpdatetime(new Date());
            appFamilyMember.setIdentity(4);
            appFamilyMemberService.save(appFamilyMember);
            return this.sucessJSON("申请成功");
        } catch (Exception e) {
            logger.error("申请加入家族异常", e);
            return this.errorJSON("系统繁忙，请稍后重试");
        }
    }

    /**
     * 族长审核申请加入成员
     *
     * @param request
     * @param mid 成员id
     * @param type,1通过，3拒绝
     * @return
     */
    @ResponseBody
    @RequestMapping("/familyMemberExamine")
    public Result familyMemberExamine(HttpServletRequest request, Integer mid, Integer type) {
        try {
            Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));
            AppUser appUser = appUserService.get(userId);
            if (StringUtils.isEmpty(appUser)) {
                return this.errorJSON("用户不存在");
            }
            AppFamilyMember appFamilyMember = new AppFamilyMember();
            appFamilyMember.setStatus(0);
            appFamilyMember.setUserid(mid);
            AppFamilyMember byId = appFamilyMemberService.findInfo(appFamilyMember);
            if (byId == null) {
                return this.errorJSON("审核成员不存在");
            }
            if (byId.getStatus() != 0) {
                return this.errorJSON("待审核成员已通过或已拒绝");
            }
            if (type != 1 && type != 3) {
                return this.errorJSON("类型错误");
            }

            AppFamily byLeaderId = appFamilyService.findByLeaderId(userId);
            if (byLeaderId == null) {
                return this.errorJSON("您不是族长不能参与审核");
            }
            if (byLeaderId.getId() != byId.getFid()) {
                return this.errorJSON("待审核成员不属于您的家族");
            }

            appFamilyMemberService.familyMemberExamine(byId.getId(), type);

            String msg = "";
            if (type == 1) {
                appFamilyService.familyMemberInc(byLeaderId.getId());//增加家族成员数

                appDailyTasController.getAwardOnce(mid, ClientConstants.TaskOnce.JOIN_FAMILY);

                AppUser auditUser = appUserService.get(mid);
                systemAlertService.joinFamily(auditUser.getTengxuncode(), byLeaderId.getFamilyname());
                msg = "已通过";
            } else if (type == 3) {
                msg = "已拒绝";
            }
            return this.sucessJSON(msg);
        } catch (Exception e) {
            logger.error("族长审核申请加入成员异常", e);
            return this.errorJSON("系统繁忙，请稍后重试");
        }
    }


    /**
     * 退出家族
     *
     * @param request
     * @param fid     家族id
     * @return
     */
    @ResponseBody
    @RequestMapping("/quitFamily")
    public Result quitFamily(HttpServletRequest request, Integer fid) {
        try {
            Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));
            AppUser appUser = appUserService.get(userId);
            if (StringUtils.isEmpty(appUser)) {
                return this.errorJSON("用户不存在");
            }
            AppFamilyMember appFamilyMember = new AppFamilyMember();
            appFamilyMember.setFid(fid);
            appFamilyMember.setUserid(userId);
            appFamilyMember.setStatus(1);
            AppFamilyMember info = appFamilyMemberService.findInfo(appFamilyMember);
            if (info == null) {
                return this.errorJSON("您未加入该家族不可退出");
            }
            AppSetup setup = appSetupService.get();
            if (setup != null && setup.getQuitFamilyForDay() > 0) {
                Integer time = setup.getQuitFamilyForDay() * 86400;
                redisUtil.set(RedisKeys.QUIT_FAMILY + userId + appUser.getLoginname(), fid, time);
            }
            appFamilyService.familyMemberDec(fid);//减少家族成员数
            appFamilyMemberService.quitFamily(info.getId());
            return this.sucessJSON("退出成功");
        } catch (Exception e) {
            logger.error("退出家族异常", e);
            return this.errorJSON("系统繁忙，请稍后重试");
        }
    }


    /**
     * 获取家族列表
     *
     * @param request
     * @param type    1同城，2附近，3日榜，4周榜
     * @return
     */
    @ResponseBody
    @RequestMapping("/getFamilyList")
    public Result getFamilyList(HttpServletRequest request, Integer type, Integer pageno ,Integer addrshi) {
        try {
            if (type != 1 && type != 2 && type != 3 && type != 4 && type != 5) {
                return this.errorJSON("列表类型错误");
            }
            if (pageno == null) {
                return this.errorJSON("页码不存在！");
            }
            Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));
            AppUser appUser = appUserService.get(userId);
            if (StringUtils.isEmpty(appUser)) {
                return this.errorJSON("用户不存在");
            }
            if(type == 1 && addrshi<=0){
                if(appUser.getShiid()!=null && appUser.getShiid()>0){
                    addrshi = appUser.getShiid();
                }
            }
            /*if (type == 1) {
                if (StringEx.isNull(appUser.getShiid())) {
                    return this.errorJSON("未获取到当前用户位置信息！");
                }
            } else if (type == 2) {
                if (StringEx.isNull(appUser.getLon()) || StringEx.isNull(appUser.getLon())) {
                    return this.errorJSON("未获取到当前用户位置信息！");
                }
            }*/
            //分页数据
            SplitPageBean splitPageBean = new SplitPageBean(pageno, 20);
            List<AppFamily> familyList = appFamilyService.getFamilyList(appUser.getLon(), appUser.getLat(), addrshi, type, appUser.getId(), splitPageBean);
            if (familyList == null || familyList.size() == 0) {
                return this.sucessPage(new ArrayList<>(), splitPageBean.getNextPageNo());
            }

            return this.sucessJSON(familyList, "获取成功");
        } catch (Exception e) {
            logger.error("获取家族列表TYPE：" + type, e);
            return this.errorJSON("系统繁忙，请稍后重试");
        }
    }

    /**
     * 家族内签到
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/punchIn")
    @Transactional(rollbackFor = Exception.class)
    public Result punchIn(HttpServletRequest request) {
        Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));
        if (userId == null) {
            return this.errorJSON("请登录");
        }
        AppQianDaoRecord familyNow = appQianDaoRecordService.getFamilyNow(userId);
        if (familyNow != null) {
            return this.errorJSON("今天已签到");
        }

        AppFamilyMember family = appFamilyMemberService.getFamily(userId);
        if (family == null) {
            return this.errorJSON("您未加入家族，不可签到");
        }

        AppUser user = appUserService.lockGet(userId);
        Integer tianshu = user.getFamilyPunchIn();
        if (tianshu.equals(7)) tianshu = 0;
        AppQianDaoRecord familyYesterday = appQianDaoRecordService.getFamilyYesterday(userId);
        if (Objects.isNull(familyYesterday)) tianshu = 0;
        AppSetup setup = appSetupService.get();
        BigDecimal punchInFamilyWard = new BigDecimal(setup.getPunchInFamilyWard());
        BigDecimal punchInFamilyPrestige = new BigDecimal(setup.getPunchInFamilyPrestige());
        if (tianshu == null || tianshu == 0) {
//            appUserService.addJindou(user.getId(), punchInFamilyWard);
            appUserService.updateZuanShi(user.getId(),punchInFamilyWard);
            AppQianDaoRecord qianDaoRecord = new AppQianDaoRecord();
            qianDaoRecord.setUserid(user.getId());
            qianDaoRecord.setNick(user.getNick());//签到用户名字
            qianDaoRecord.setPic(user.getPic());//用户头像
            qianDaoRecord.setUserid(user.getId());//用户表示
            qianDaoRecord.setPhone(user.getLoginname());
            qianDaoRecord.setJinbi(punchInFamilyWard);
            qianDaoRecord.setCreatetime(new Date());
            qianDaoRecord.setStatus(1);
            qianDaoRecord.setIsFamily(1);
            appQianDaoRecordService.saveOrUpdate(qianDaoRecord);
//            appMingxiJinbiService.addMingxi(user.getId(), punchInFamilyWard, 1, "家族内签到");
            appMingXiZuanShiService.addMingxi(user.getId(),punchInFamilyWard,1,"家族内签到");
            appUserService.familyPunchIn(1, user.getId());
            appFamilyPrestigeService.addPrestisge(3, setup.getPunchInFamilyPrestige(), user.getId(), "家族签到", family.getFid());
            return this.sucessJSON("签到获得" + setup.getPunchInFamilyWard() + "钻石", "签到成功");
        } else if (tianshu >= 1 && tianshu <= 6) {
            appUserService.updateZuanShi(user.getId(),punchInFamilyWard);
//            appUserService.addJindou(user.getId(), punchInFamilyWard);
            AppQianDaoRecord qianDaoRecord = new AppQianDaoRecord();
            qianDaoRecord.setUserid(user.getId());
            qianDaoRecord.setNick(user.getNick());//签到用户名字
            qianDaoRecord.setPic(user.getPic());//用户头像
            qianDaoRecord.setUserid(user.getId());//用户表示
            qianDaoRecord.setPhone(user.getLoginname());
            qianDaoRecord.setJinbi(punchInFamilyWard);
            qianDaoRecord.setCreatetime(new Date());
            qianDaoRecord.setStatus(1);
            qianDaoRecord.setIsFamily(1);
            appQianDaoRecordService.saveOrUpdate(qianDaoRecord);
            appUserService.familyPunchIn(tianshu + 1, user.getId());
//            appMingxiJinbiService.addMingxi(user.getId(), punchInFamilyWard, 1, "家族内签到");
            appMingXiZuanShiService.addMingxi(user.getId(),punchInFamilyWard,1,"家族内签到");
            appFamilyPrestigeService.addPrestisge(3, setup.getPunchInFamilyPrestige(), user.getId(), "家族签到", family.getFid());
            return this.sucessJSON("连续签到获得" + setup.getPunchInFamilyWard() + "钻石", "签到成功");
        }
        return this.sucessJSON("签到成功");
    }

    /**
     * 获取家族详情
     *
     * @param request
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping("/getFamilyDetail")
    public Result getFamilyDetail(HttpServletRequest request, Integer id) {
        try {
            Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));
            AppUser appUser = appUserService.get(userId);
            if (StringUtils.isEmpty(appUser)) {
                return this.errorJSON("用户不存在");
            }
            if (StringEx.isNull(id)) {
                return this.errorJSON("家族不存在");
            }
            AppFamily appFamily = appFamilyService.findbyId(id);
            if (appFamily == null) {
                return this.errorJSON("家族不存在");
            }
            AppUser leaderInfo = appUserService.get(appFamily.getLeaderid());
            AppFamilyPrestige dayPrestigenum = appFamilyPrestigeService.getDayPrestige(appFamily.getLeaderid());
            if(dayPrestigenum.getDayPrestigenum()==null || dayPrestigenum.getDayPrestigenum().compareTo(BigDecimal.ZERO)<=0){
                leaderInfo.setDayPrestige(BigDecimal.ZERO);
            }else{
                leaderInfo.setDayPrestige(dayPrestigenum.getDayPrestigenum());
            }


            //判断用户是否是贵族
            if (leaderInfo.getIsguizu() == 1) {
                //是贵族
                //根据贵族id  获取贵族图标
                String medal = guizuCacheMap.get(leaderInfo.getNobleid());
                leaderInfo.setMedal(medal);
            } else {
                leaderInfo.setMedal("");
            }
            leaderInfo.setAge(AgeUtils.getAgeByBirth(leaderInfo.getBirthday()));
            if(leaderInfo.getVipEndDate() != null) {
                leaderInfo.setIsVip(TimeUtils.afterNow(leaderInfo.getVipEndDate())? 1: 0);
            }
            appFamily.setLeaderInfo(leaderInfo);
            List<AppFamilyMember> familyMemberByFid = appFamilyMemberService.getFamilyMemberByFid(id);
            appFamily.setMemberInfo(familyMemberByFid);
            List<AppFamilyMember> allFamilyMemberByFid = appFamilyMemberService.getAllFamilyMemberByFid(id);
            int isAddFamily = 2;
            for (AppFamilyMember member:allFamilyMemberByFid){
                if(member.getUserid().equals(appUser.getId())){
                    if(member.getStatus() == 0){
                        isAddFamily = 0;
                    }else if(member.getStatus() == 1){
                        isAddFamily = 1;
                    }
                }
            }
            appFamily.setIsAddFamily(isAddFamily);
            Integer rankingByPrestige = appFamilyService.findRankingByPrestige(id, 3);
            Integer rankingByPrestige1 = appFamilyService.findRankingByPrestige(id, 2);
            appFamily.setAllRanking(rankingByPrestige);
            appFamily.setWeekRanking(rankingByPrestige1);
            AppFamilySetLevel levelInfoByLevel = appFamilySetLevelService.getLevelInfoByLevel(appFamily.getFamilylevel());
            appFamily.setLevelMaxPrestige(levelInfoByLevel.getMaxPrestige());
            appFamily.setFamilyMaxCount(levelInfoByLevel.getFamilyMaxCount());
            return this.sucessJSON(appFamily, "成功");
        } catch (Exception e) {
            logger.error("获取家族详情异常", e);
            return this.errorJSON("系统繁忙，请稍后重试");
        }
    }


    /**
     * 获取已加入的家族
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/getMyFamily")
    public Result getMyFamily(HttpServletRequest request) {
        try {
            Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));
            AppUser appUser = appUserService.get(userId);
            if (StringUtils.isEmpty(appUser)) {
                return this.errorJSON("用户不存在");
            }
            AppFamilyMember byUserId = appFamilyMemberService.findByUserId(appUser.getId());
            /*if (byUserId == null || byUserId.getStatus() != 1) {
                return this.errorJSON("未加入家族");
            }*/
            if (byUserId == null) {
                return this.errorJSON("未加入家族");
            }
            AppFamily appFamily = appFamilyService.findFamilyById(byUserId.getFid());
            if(appFamily!=null && appFamily.getStatus()==0){
                AppUser appUser1 = appUserService.get(appFamily.getLeaderid());
                appFamily.setLeaderName(appUser1.getNick());
                List<AppFamilyMember> familyMemberByFid = appFamilyMemberService.getFamilyMemberByFid(byUserId.getFid());
                appFamily.setMemberInfo(familyMemberByFid);
            }
            return this.sucessJSON(appFamily, "获取成功");
        } catch (Exception e) {
            logger.error("获取我的家族异常", e);
            return this.errorJSON("系统繁忙，请稍后重试");
        }
    }


    /**
     * 获取家族身份列表
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/getIdentityList")
    public Result getIdentityList(HttpServletRequest request) {
        try {
            Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));
            AppUser appUser = appUserService.get(userId);
            if (StringUtils.isEmpty(appUser)) {
                return this.errorJSON("用户不存在");
            }
            List<AppFamilyIdentity> identityList = appFamilyIdentityService.getIdentityList(2);
            return this.sucessJSON(identityList, "获取成功");
        } catch (Exception e) {
            logger.error("获取家族身份列表异常", e);
            return this.errorJSON("系统繁忙，请稍后重试");
        }
    }


    /**
     * 指定家族成员身份
     *
     * @param request
     * @param MemberId   家族成员id
     * @param identityId 身份id
     * @return
     */
    @ResponseBody
    @RequestMapping("/appointMemberIdentity")
    public Result appointMemberIdentity(HttpServletRequest request, Integer MemberId, Integer identityId) {
        try {
            Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));
            AppUser appUser = appUserService.get(userId);
            if (StringUtils.isEmpty(appUser)) {
                return this.errorJSON("用户不存在");
            }
            AppFamilyMember byUserId = appFamilyMemberService.findByUserId(MemberId);
            if (byUserId == null || byUserId.getStatus() != 1) {
                return this.errorJSON("家族成员不存在");
            }
            AppFamily appFamily = appFamilyService.findbyId(byUserId.getFid());
            if (appFamily == null) {
                return this.errorJSON("家族不存在");
            }
            if (!appFamily.getLeaderid().equals(appUser.getId())) {
                return this.errorJSON("您不是该家族的族长，不可指定成员身份");
            }
            if (appFamily.getLeaderid() == MemberId) {
                return this.errorJSON("族长不可指定自己身份");
            }
            AppFamilyIdentity appFamilyIdentity = appFamilyIdentityService.get(identityId);
            if (appFamilyIdentity == null) {
                return this.errorJSON("家族身份不存在");
            }
            appFamilyMemberService.updateMemberIdentity(byUserId.getId(), identityId);
            return this.sucessJSON("指定成功");
        } catch (Exception e) {
            logger.error("获取家族身份列表异常", e);
            return this.errorJSON("系统繁忙，请稍后重试");
        }
    }


    /**
     * 修改家族公告
     * @param request
     * @param familyNotice 家族公告
     * @return
     */
    @ResponseBody
    @RequestMapping("/saveFamilyNotice")
    public Result saveFamilyNotice(HttpServletRequest request,String familyNotice)
    {
        try {
            if(StringUtils.isEmpty(familyNotice))
            {
                return this.errorJSON("请填写公告内容");
            }
            if(familyNotice.length()>100){
                return this.errorJSON("公告字数不能大于100字");
            }
            Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));
            AppUser appUser = appUserService.get(userId);
            if (StringUtils.isEmpty(appUser)) {
                return this.errorJSON("用户不存在");
            }
            AppFamily byLeaderId = appFamilyService.findByLeaderId(appUser.getId());
            if(byLeaderId == null || byLeaderId.getStatus()!=0){
                return this.errorJSON("家族不存在或被封禁");
            }
            appFamilyService.saveFamilyNotice(byLeaderId.getId(),familyNotice);
            return this.sucessJSON("成功");
        }catch (Exception e){
            logger.error("修改家族公告异常", e);
            return this.errorJSON("系统繁忙，请稍后重试");
        }
    }

    /**
     * 修改家族头像
     * @param request
     * @param pic 头像地址
     * @return
     */
    @ResponseBody
    @RequestMapping("/saveUploadPic")
    public Result saveUploadPic(HttpServletRequest request,String pic)
    {
        if(StringUtils.isEmpty(pic)){
            return this.errorJSON("请上传家族头像");
        }
        Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));
        AppUser appUser = appUserService.get(userId);
        if (StringUtils.isEmpty(appUser)) {
            return this.errorJSON("用户不存在");
        }
        AppFamily byLeaderId = appFamilyService.findByLeaderId(appUser.getId());
        if(byLeaderId == null || byLeaderId.getStatus()!=0){
            return this.errorJSON("家族不存在或被封禁");
        }
        appFamilyService.saveUploadPic(byLeaderId.getId(),pic);
        return this.sucessJSON("成功");
    }


    /**
     * 修改家族名称
     * @param request
     * @param familyName 家族名称
     * @return
     */
    @ResponseBody
    @RequestMapping("/saveFamilyName")
    public Result saveFamilyName(HttpServletRequest request,String familyName)
    {
        if(StringUtils.isEmpty(familyName)){
            return this.errorJSON("请输入家族名称");
        }
        if(familyName.length()>30){
            return this.errorJSON("家族名称不能大于30字");
        }
        Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));
        AppUser appUser = appUserService.get(userId);
        if (StringUtils.isEmpty(appUser)) {
            return this.errorJSON("用户不存在");
        }
        AppFamily byLeaderId = appFamilyService.findByLeaderId(appUser.getId());
        if(byLeaderId == null || byLeaderId.getStatus()!=0){
            return this.errorJSON("家族不存在或被封禁");
        }
        appFamilyService.saveFamilyName(byLeaderId.getId(),familyName);
        return this.sucessJSON("成功");
    }

    /**
     * 踢出家族
     * @param request
     * @param memberId 家族成员id
     * @return
     */
    @ResponseBody
    @RequestMapping("/kickOutMember")
    public Result kickOutMember(HttpServletRequest request,Integer memberId)
    {
        if(StringEx.isNullOrLing(memberId)){
            return this.errorJSON("请选择家族成员");
        }
        Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));
        AppUser appUser = appUserService.get(userId);
        if (StringUtils.isEmpty(appUser)) {
            return this.errorJSON("用户不存在");
        }
        if(memberId.equals(appUser.getId())){
            return this.errorJSON("不能踢出自己");
        }
        AppFamily byLeaderId = appFamilyService.findByLeaderId(appUser.getId());
        if(byLeaderId == null || byLeaderId.getStatus()!=0){
            return this.errorJSON("家族不存在或被封禁");
        }
        AppFamilyMember byUserId = appFamilyMemberService.findByUserId(memberId);
        if(byUserId==null || byUserId.getStatus()!=1){
            return this.errorJSON("家族成员不存在");
        }

        appFamilyService.kickOutMember(byLeaderId.getId(),byUserId.getId());

        return this.sucessJSON("已踢出");
    }


    /**
     * 获取家族成员列表
     * @param request
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping("/getFamilyMembers")
    public Result getFamilyMembers(HttpServletRequest request,Integer id)
    {
        if(StringEx.isNullOrLing(id)){
            return this.errorJSON("请选择家族");
        }
        Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));
        AppUser appUser = appUserService.get(userId);
        if (StringUtils.isEmpty(appUser)) {
            return this.errorJSON("用户不存在");
        }
        AppFamily appFamily = appFamilyService.findbyId(id);
        if(appFamily == null || appFamily.getStatus() != 0){
            return this.errorJSON("家族不存在");
        }
        List<AppFamilyMember> familyMemberByFid = appFamilyMemberService.getFamilyMemberByFid(id);
        return this.sucessJSON(familyMemberByFid,"成功");
    }

    /**
     * 解散家族
     * @param request
     * @param id 家族id
     * @return
     */
    @ResponseBody
    @RequestMapping("/familyDismiss")
    public Result familyDismiss(HttpServletRequest request,Integer id)
    {
        if(StringEx.isNullOrLing(id)){
            return this.errorJSON("请选择家族");
        }
        Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));
        AppUser appUser = appUserService.get(userId);
        if (StringUtils.isEmpty(appUser)) {
            return this.errorJSON("用户不存在");
        }
        AppFamily appFamily = appFamilyService.findbyId(id);
        if(appFamily == null || appFamily.getStatus() != 0){
            return this.errorJSON("家族不存在");
        }
        appFamilyService.familyDismiss(id);
        return this.sucessJSON("已解散");
    }




}
